<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-row>
        <el-col>
          <el-button type="primary" size="mini" @click="addRolesDialogIsShow = true">添加角色</el-button>
        </el-col>
      </el-row>
      <!-- 角色列表展示 -->
      <el-table :data="rolesList" border stripe size="mini">
        <!-- 表格展开属性 expand展开 index自动生序 -->
        <el-table-column label="明细" type="expand">
          <!-- 自定义模板渲染权限 -->
          <template slot-scope="scope">
            <el-row v-for="(item1, i) in scope.row.children" :key="item1.id" :class="{ bdbottom: true, topborder: i == 0, vcenter: true }">
              <el-col :span="5">
                <el-tag type="primary" closable size="medium" @close="removepower(scope.row, item1.id)"> {{ item1.authName }} </el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <el-col :span="19">
                <el-row v-for="(item2, i) in item1.children" :key="item2.id" :class="{ topborder: i !== 0, vcenter: true }">
                  <el-col :span="6">
                    <el-tag type="success" closable size="small" @close="removepower(scope.row, item2.id)"> {{ item2.authName }} </el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag type="warning" size="mini" closable v-for="item3 in item2.children" :key="item3.id" @close="removepower(scope.row, item3.id)"> {{ item3.authName }} </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column label="序号" type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" icon="el-icon-edit" @click="editRolesById(scope.row.id)">编辑</el-button>
            <el-button size="mini" type="danger" icon="el-icon-delete" @click="deleteRoleById(scope.row.id)">删除</el-button>
            <el-button size="mini" type="warning" icon="el-icon-setting" @click="showPowerDialog(scope.row)">分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加角色对话框 :visible.sync绑定显示或隐藏-->
    <el-dialog title="添加角色" :visible.sync="addRolesDialogIsShow" width="50%" @close="formRest">
      <el-form :model="addRolesForm" :rules="addRolesRules" ref="addRolesForm" label-width="80px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addRolesForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addRolesForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addRolesDialogIsShow = false">取 消</el-button>
        <el-button type="primary" @click="addRoles">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑角色对话框 :visible.sync绑定显示或隐藏-->
    <el-dialog title="添加角色" :visible.sync="editRolesDialogIsShow" width="50%">
      <el-form :model="editRolesForm" :rules="editRolesRules" ref="editRolesForm" label-width="80px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editRolesForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editRolesForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editRolesDialogIsShow = false">取 消</el-button>
        <el-button type="primary" @click="editRoles">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配权限结构 :visible.sync控制对话框显隐-->
    <el-dialog title="分配权限" :visible.sync="addPowerDialogIsShow" width="35%" @close='emtyDefault'>
      <el-tree  ref='treeRef' :data="powerTreeList" :props="treeProps" node-key='id' show-checkbox default-expand-all
      :default-checked-keys='defaultKeys'
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addPowerDialogIsShow = false">取 消</el-button>
        <el-button type="primary" @click="addPower">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'roles',
  data() {
    return {
      rolesList: [],
      //控制添加角色对话框显影
      addRolesDialogIsShow: false,
      //添加角色对象也就是表单v-model绑定的数据，将来要发给后台的
      addRolesForm: {
        roleName: '',
        roleDesc: '',
      },
      // 定义添加表单校验规则
      addRolesRules: {
        roleName: [
          { required: true, message: '请输入活动名称', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' },
        ],
      },
      //编辑角色对话框显影
      editRolesDialogIsShow: false,
      //编辑角色对象也就是表单v-model绑定的数据，将来要发给后台的
      editRolesForm: {
        roleName: '',
        roleDesc: '',
      },
      // 定义编辑表单校验规则
      editRolesRules: {
        roleName: [
          { required: true, message: '请输入活动名称', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' },
        ],
      },
      //分配权限显隐
      addPowerDialogIsShow:false,
      //权限树列表
      powerTreeList:[],
      //树型组件配置选项
      treeProps:{
          label:'authName',
          children:'children'
      },
      defaultKeys:[],
      //当前分配权限对象Id
      crentRoleId:''
    }
  },
  created() {
    this.getRolesList()
  },
  methods: {
    //获取角色列表
    async getRolesList() {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色列表数据失败！')
      }
      this.rolesList = res.data
    //   console.log(this.rolesList)
    },
    //添加角色方法
    addRoles() {
      this.$refs.addRolesForm.validate(async (valid) => {
        if (!valid) {
          return this.$message.error('请输入正确的角色名称')
        }
        const { data: res } = await this.$http.post('roles', this.addRolesForm)
        if (res.meta.status !== 201) {
          return this.$message.error('角色添加失败！')
        }
        this.addRolesDialogIsShow = false
        this.getRolesList()
        this.$message.success('角色添加成功！')
      })
    },
    //对话框关闭时表单重置 resetFields方法为elementui提供
    formRest() {
      this.$refs.addRolesForm.resetFields()
    },
    //向后台查询要编辑的角色
    async editRolesById(id) {
      this.editRolesDialogIsShow = true
      const { data: res } = await this.$http.get(`roles/${id}`)
      if (res.meta.status !== 200) {
        return this.$message.error('角色查询失败！')
      }
      this.editRolesForm = res.data
    },
    //编辑上面查询到的角色（通过发送给后台修改）
    editRoles() {
      this.$refs.editRolesForm.validate(async (valid) => {
        if (!valid) {
          return
        }
        this.editRolesDialogIsShow = false
        const { data: res } = await this.$http.put(`roles/${this.editRolesForm.roleId}`, {
          roleName: this.editRolesForm.roleName,
          roleDesc: this.editRolesForm.roleDesc,
        })
        // console.log(res)
        if (res.meta.status !== 200) {
          return this.$message.error('角色修改失败！')
        }
        this.getRolesList()
        this.$message.success('修改角色成功！')
      })
    },
    //删除角色
    deleteRoleById(id) {
      //confirm弹窗由elementui messageBox提供
      this.$confirm('确定要删除该角色么？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(async () => {
          const { data: res } = await this.$http.delete(`roles/${id}`)
          if (res.meta.status !== 200) {
            this.$message.error('删除角色失败！')
          }
          this.getRolesList()
          this.$message.success('已成功删除角色！')
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除',
          })
        })
    },
    //删除权限功能
    removepower(crentUser, id) {
      this.$confirm('确定要删除该权限么?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(async () => {
          const { data: res } = await this.$http.delete(`roles/${crentUser.id}/rights/${id}`)
          if (res.meta.status !== 200) {
            return this.$message.error('删除权限失败！')
          }
          crentUser.children = res.data
          this.$message.success('删除权限成功！')
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除',
          })
        })
    },
    //分配权限
    async showPowerDialog(role){
        this.addPowerDialogIsShow = true
        const {data:res} = await this.$http.get('rights/tree')
        if(res.meta.status !==200){
            return this.$message.error('获取权限数据失败！')
        }
        this.powerTreeList = res.data
        //  console.log(this.powerTreeList)
        this.getLeafKeys(role)
        // console.log(role)
        this.crentRoleId = role.id
    },
    async addPower(){
        //getCheckedKeys是elementui tree组件提供获取已勾选对象id,因为上面组件结构node-key绑定的就是id
        const keysArray = this.$refs.treeRef.getCheckedKeys().concat(this.$refs.treeRef.getHalfCheckedKeys())
        // console.log(keysArray)
        //向后台发送请求分配角色权限
        const{data:res} = await this.$http.post(`roles/${this.crentRoleId}/rights`,{
            rids:keysArray.join(',')
        })
        if(res.meta.status !==200){
            return this.$message.error('分配角色失败！')
        }
        this.addPowerDialogIsShow = false
        this.$message.success('角色权限分配成功！')
        this.getRolesList()
    },
    //关闭分配权限Dialog对话框时
    emtyDefault(){
        this.defaultKeys = []
    },
    //获取角色最底层权限ID
    getLeafKeys(node){
        //判断角色是否还有children
        if(!node.children){
           return this.defaultKeys.push(node.id)
        }
        node.children.forEach(item => {
            this.getLeafKeys(item)
        })
    }
  },
}
</script>

<style lang="less" scoped>
.el-tag {
  margin: 6px;
}
.bdbottom {
  border-bottom: 0.3px solid #ccc;
}
.topborder {
  border-top: 0.2px solid #ddd;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>